import connection from "@/app/database.ts";
import { formatSql } from "@/utils/formate";
import { addHandle, deleteHandle, listHandle, updateHandle } from "@/utils/sql";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import uploadService from "./upload.service";

class UserService {
  // 添加用户
  async add(user: API.userItem) {
    return await addHandle<API.userItem>(user, "user");
  }

  // 根据用户名获取用户
  async getUserByUsername(username: string): Promise<API.userItem | null> {
    const statement = "SELECT * FROM user WHERE username = ?";
    const [rows] = await connection.execute<RowDataPacket[]>(statement, [
      username,
    ]);
    return rows.length > 0 ? (rows[0] as API.userItem) : null;
  }

  // 根据ID获取用户
  async getUserByID(id: number): Promise<API.userItem | null> {
    const statement = "SELECT * FROM user WHERE id = ?";
    const [rows] = await connection.execute<RowDataPacket[]>(statement, [id]);
    return rows.length > 0 ? (rows[0] as API.userItem) : null;
  }

  // 获取用户列表（分页）
  async list(params: API.userList): Promise<API.ResponseApi<API.userItem>> {
    return await listHandle<API.userList, API.userItem>(params, "user");
  }

  // 更新用户信息
  async update(user: API.userItem): Promise<boolean> {
    return await updateHandle<API.userItem>(user, "user");
  }

  // 删除用户
  async delete(ids: number[]): Promise<boolean> {
    try {
      const [rows] = await connection.execute<RowDataPacket[]>(
        `
      SELECT avatar FROM user WHERE id IN (${ids.map(() => "?").join(", ")})
      `,
        ids
      );
      await uploadService.deleteFiles(
        (rows as { avatar: string }[]).map(({ avatar }) => avatar)
      );
    } catch (error: any) {
      throw new Error(error || "头像删除失败");
    }
    return await deleteHandle(ids, "user");
  }
}

export default new UserService();
